package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import com.sun.jersey.json.impl.provider.entity.JSONArrayProvider;
import jdk.nashorn.internal.parser.JSONParser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.heima.common.constants.wemedia.WemediaConstants.WM_CONTENT_REFERENCE;

/**
 *
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    // 查询文章列表
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 检查参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        // ThreadLocal中获取用户信息
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"您需要先登陆");
        }
        // 新建分页查询
        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());
        // 新建条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 如果已经登陆则条件中加入，查询当前登陆用户的文章
        wrapper.eq(WmNews::getUserId,wmUser.getId());
        // 判断是否有文章状态
        if (dto.getStatus() != null){
            // 有则加入条件中
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        // 判断是否有关键字，有则加入条件
        if (dto.getKeyword() != null){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        // 判断是否有频道信息，有则加入条件
        if (dto.getChannelId() != null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        // 判断是否包含发布日期
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        // 进行分页查询
        IPage<WmNews> pageResult = page(wmNewsPage, wrapper);
        // 封装查询结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        List<WmNews> records = pageResult.getRecords();
        pageResponseResult.setHost(webSite);
        pageResponseResult.setData(records);

        // 返回结果
        return pageResponseResult;
    }

    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    WmMaterialMapper wmMaterialMapper;

    @Resource
    private KafkaTemplate kafkaTemplate;
    @Override
    public ResponseResult saveNews(WmNewsDto wmNewsDto, Short isSubmit) {
        // 检查封装参数
        if (wmNewsDto == null || wmNewsDto.getContent() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 是否登陆
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"需要进行登陆");
        }
        // 将dto拷贝到新建的WmNews对象中
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);

        // 如果自动生成封面状态type设置为null
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            // 设置为null
            wmNews.setType(null);
        }
        // images数组转成字符串
        List<String> images = wmNewsDto.getImages();
        // 转成字符串并把每个地址前面的去掉（webSite）
        String imagesStr = images.stream().map((url) -> url.replace(webSite, ""))
                .collect(Collectors.joining(","));
        wmNews.setImages(imagesStr);
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(wmUser.getId());
        wmNews.setSubmitedTime(new Date());
        // 上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        // 判断id是否为空，为空则保存，不为空则查找
        if (wmNewsDto.getId() == null){
            save(wmNews);
        }else {
            // 如果不为空，删除素材与文章的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            // 修改文章
            updateById(wmNews);
        }
        // 判断审核状态，唯一发送kafka等待审核
        // 4 发消息给admin审核文章
        Map map = new HashMap();
        map.put("wmNewsId", wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        // 将内容转为list<Map>集合
        // 使用JSON解析成map类型
        List<Map> imageMaps = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        // 遍历map集合,如果类型为image替换前缀存入集合
        List<String> materials = parseContentImages(imageMaps);
        // 根据图片列表和用户id获取素材列表
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() > 0){
            // 关联图片与素材
            saveRelativeInfoForContent(materials, wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }

        if (isSubmit == WmNews.Status.SUBMIT.getCode()){
            saveRelativeInfoForCover(wmNewsDto,materials, wmNews);
        }
        // 返回结果
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        // 根据id查询
        if (id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        // 返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 如果已经上架不能删除
        WmNews wmNews = getById(id);
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布,不能删除");
        }
        // 去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        // 删除文章
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(dto.getId());

        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        update(Wrappers.<WmNews>lambdaUpdate()
                .set(WmNews::getEnable,dto.getEnable())
                .eq(WmNews::getId,dto.getId()));
        if (wmNews.getArticleId() != null){
            Map<String, Object> map = new HashMap<>();
            map.put("enable",wmNews.getEnable());
            map.put("articleId",wmNews.getArticleId());
            // 发送消息
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public List<Integer> findRelease() {
        // 查询已经通过审核的文章信息
        List<WmNews> wmNewsList = list(Wrappers.<WmNews>lambdaQuery().in(WmNews::getStatus, 4, 8)
                .le(WmNews::getPublishTime, new Date()));
        // 将集合映射成id集合
        List<Integer> idList = wmNewsList.stream()
                .map(WmNews::getId)
                .collect(Collectors.toList());
        return idList;
    }

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        // 检查参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        int page = (dto.getPage() - 1) * dto.getSize();
        dto.setPage(page);
        // 查询列表
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        // 查询有多少条数据
        long listCount = wmNewsMapper.findListCount(dto);
        // 封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(page, dto.getSize(), (int) listCount);
        pageResponseResult.setData(listAndPage);

        return pageResponseResult;
    }

    @Resource
    WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        // 检查参数
        if(id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 查询作者信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        // 封装返回信息
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;

    }

    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        // 检查参数
        if(dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据dto中的内容进行修改
        // 先查询
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 更改状态
        wmNews.setStatus(status);
        // 判断是否有原因
        if (dto.getMsg() != null){
            wmNews.setReason(dto.getMsg());
        }
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, List<String> materials, WmNews wmNews) {
        // 前端选择的图
        List<String> images = wmNewsDto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())){
            // 自动获取封面，获取集合的大小分别判断
            if (materials.size() > 0 && materials.size() <= 2){
                // 单图
                images = materials.stream().limit(1).collect(Collectors.toList());
                // 设置type的值
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (materials.size() > 2) { // 多图
                images =  materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {  // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                // 将图片集合 转为字符串  url1,url2,url3
                wmNews.setImages(imageListToStr(images,webSite));
            }
            updateById(wmNews);
        }
        // 保存图片列表和素材的关系
        if (images != null && images.size() > 0) {
            images = images.stream()
                    .map(x->x.replace(webSite,"")
                            .replace(" ","")).collect(Collectors.toList());
            saveRelativeInfoForContent(images, wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    private String imageListToStr(List<String> images, String webSite) {
        return images.stream()  // 获取流
                .map((url) -> url.replace(webSite, ""))  // 对流数据的中间操作
                .collect(Collectors.joining(","));
    }

    private void saveRelativeInfoForContent(List<String> materials, Integer newsId,Short type) {
        // 查询文章中图片对应的素材id
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materials)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        // 检查素材列表
        if (wmMaterials == null || wmMaterials.size() == 0){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 遍历结果表，封装 id到集合中,用于mapper中的方法参数
        ArrayList<Integer> materialIds = new ArrayList<>();
        Map<String, Integer> materialMap = wmMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String material : materials) {
            Integer id = materialMap.get(material);
            if (id == null) {
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            materialIds.add(id);
        }
        wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);
    }

    private List<String> parseContentImages(List<Map> imageMaps) {
        /*List<String> imageList = new ArrayList<>();
        for (Map imageMap : imageMaps) {
            if (imageMap.get("type").equals("image")){
                // 获取value,替换前缀,存入集合
                imageList.add(imageMap.get("value").
                        toString().replace(webSite,""));
            }
        }*/
        return imageMaps.stream().filter(map -> map.get("type").equals("image"))
                .map(map -> (String) map.get("value"))
                .map(str -> str.replace(webSite, ""))
                .collect(Collectors.toList());
    }

}
